package com.bang.daybreak.common.util;

import com.aspose.words.Document;
import com.aspose.words.SaveOptions;
import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * Created by xli on 2019/5/16.
 */
public class WordUtil {
    private static Configuration configuration = null;

    private WordUtil() {
        throw new AssertionError();
    }

    /**
     * 根据模板生成相应的文件
     *
     * @param root    保存数据的map
     * @param ftlName 模板文件name
     * @return
     */
    public static synchronized ByteArrayOutputStream process(Map<?, ?> root, String ftlName) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        if (null == configuration) {
            // 这里Configurantion对象不能有两个，否则多线程访问会报错
            configuration = new Configuration(Configuration.VERSION_2_3_23);
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassicCompatible(true);
        }
        configuration.setClassForTemplateLoading(WordUtil.class, "/static/ftl/");

        Template t = null;
        try {
            t = configuration.getTemplate(ftlName);
            Writer w = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            // 这里w是一个输出地址，可以输出到任何位置，如控制台，网页等
            t.process(root, w);
            w.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return outputStream;
    }

    /**
     * 下载word模板
     *
     * @param request  request
     * @param response response
     * @param doc      document
     * @param file     file
     * @throws Exception
     */
    public static void documentWriteWord(HttpServletRequest request, HttpServletResponse response, Document doc, File file)
            throws Exception {
        String fileName = file.getName();
        // 必要地清除response中的缓存信息
        response.reset();
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-disposition",
                    "attachment;" + UserAgentUtil.encodeFileName(request, fileName));
            javax.servlet.ServletOutputStream out = response.getOutputStream();
            doc.save(out, SaveOptions.createSaveOptions(fileName));
            out.flush();
            out.close();
            doc.cleanup();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
